package com.mapfinal.server.auth;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.mapfinal.server.auth.model.AuthRule;
import com.mapfinal.server.auth.model.User;

public class AuthInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		String target = inv.getActionKey();
		if(target.startsWith("/api")) {
			inv.invoke();
			return;
		}
		String userName = getUser(inv);
		inv.getController().set("login", userName);
		AuthRule rule = AuthRule.service().findFirstByCacheAndName(target);
		if(rule==null || rule.getStatus()==0) {
			//target不用权限
			if(rule==null) createRule(target);
			inv.invoke();
		} else {
			if(StrKit.notBlank(userName)) {
				/*
				Users user = Users.service().findByUserName(userName);
				boolean flag = AuthAccess.service().hasRule(user.getId(), rule.getId());
				if(!flag) {
					//无权限
					inv.getController().renderError(403);
					return;
				} else {
					//有权限
					inv.getController().setAttr("user", user);
					inv.invoke();
				}
				*/
				User user = AuthLoginCache.getLoginUser(userName);
				if(user==null) {
					//未登录
					inv.getController().redirect("/auth/login");
				} else if(rule.getStatus()==2) {
					//有权限
					inv.getController().setAttr("user", user.removeSecretInfo());
					inv.invoke();
				} else {
					boolean flag = user.hasRule(rule.getId());
					if(!flag) {
						//无权限
						inv.getController().renderError(403);
						return;
					} else {
						//有权限
						inv.getController().setAttr("user", user.removeSecretInfo());
						inv.invoke();
					}
				}
			} else {
				//未登录
				inv.getController().redirect("/auth/login");
			}
		}
	}
	
	public String getUser(Invocation inv) {
		//session的方式
		String userName = inv.getController().getSessionAttr("user");
		if(StrKit.isBlank(userName)) {
			//token的方式
			
		}
		System.out.println("login user is : " + userName);
		
		return userName;
	}
	
	public void createRule(String target) {
		AuthRule rule = new AuthRule();
		rule.setModule("System");
		rule.setType("sys_url");
		rule.setName(target);
		rule.setTitle(target.substring(target.lastIndexOf("/")+1));
		rule.setValue(target.substring(1).replaceAll("/", ":"));
		rule.setStatus(0);
		rule.save();
	}
}
